package com.yundingai.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import com.yundingai.domain.entity.AllUser;
import com.yundingai.domain.entity.vo.AllUserVo;
import com.yundingai.domain.vo.LoginVo;
import com.yundingai.exception.BusinessException;
import com.yundingai.service.AllUserService;
import com.yundingai.service.UserSocialDataService;
import com.yundingai.utils.JwtUtil;
import com.yundingai.utils.RedisUtils;
import com.yundingai.vm.ResponseResult;
import com.yundingai.vm.constant.RedisConstant;
import com.yundingai.vm.enums.ResultStatusEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.web.bind.annotation.*;

import java.awt.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author zhaoj
 * @Date 2025/7/25 10:56
 * @Description 用于接收用户认证类请求的接口
 **/
@RestController
@RequestMapping("auth")
public class AuthController {

    @Autowired
    private RedisUtils redis;
    @Autowired
    private AllUserService allUserService;
    @Autowired
    private UserSocialDataService userSocialDataService;

    private static final String REDIS_REFIX = "REDIS_CODE_REFIX_ID";

    //登录的方法
    @PostMapping("/login")
    public ResponseResult login(@RequestBody AllUserVo allUserVo, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();
        //验证码校验
        String codeId = allUserVo.getCodeId(); // 获取验证码ID
        String verifyCode = allUserVo.getVerifyCode(); // 获取用户输入的验证码
        String redisCode = redis.get(codeId); // 从Redis获取存储的验证码
        if (redisCode == null || !redisCode.equalsIgnoreCase(verifyCode)) {
            // 验证码错误
            return ResponseResult.errorResult(ResultStatusEnum.CODE_ERROR);
        }
        //用户名密码校验
        LoginVo loginVo = allUserService.login(allUserVo.getUsername(), allUserVo.getPassword());
        if (loginVo == null) {
            // 用户名或密码错误
            return ResponseResult.errorResult(ResultStatusEnum.LOGIN_ERROR);
        }
        //防止重复登录逻辑
        Integer userId = loginVo.getUserId();
        //生成新Token
        String newToken = JwtUtil.generateToken(loginVo);
        //存储(覆盖)到Redis（记录用户当前Token和Token对应用户）
        redis.set(RedisConstant.USER_LOGIN_KEY + userId, newToken, RedisConstant.TOKEN_EXPIRE);
        // 将Token返回给前端
        loginVo.setToken(newToken);
        return ResponseResult.okResult(loginVo);
    }

    //处理用户登出请求（用户重复登录）
    @PostMapping("/logout")
    public ResponseResult logout(HttpServletRequest request) {
        // 从请求头获取Token
        String userToken = request.getHeader("Authorization");
        if (userToken != null && !userToken.isEmpty()) {
            // 解析Token获取用户ID
            Integer userId = JwtUtil.getUserId(userToken);
            // 从Redis获取当前用户的Token
            String redisToken = redis.get(RedisConstant.USER_LOGIN_KEY + userId);
            // 验证Token有效性
            if (userId != null && redisToken != null && redisToken.equals(JwtUtil.handlePrefix(userToken))) {
                // 删除Redis中的Token
                redis.del(RedisConstant.USER_LOGIN_KEY + userId);
            }
            //如果非用户当前登录设备调用logout方法则不删除token
        }
        return ResponseResult.okResult();
    }


    @PostMapping("/register")
    public ResponseResult register(@RequestBody AllUser allUser) {
        allUserService.register(allUser.getUsername(), allUser.getPassword(), allUser.getEmail());
        return ResponseResult.okResult();
    }

    /**
     * 生成验证码
     */
    @RequestMapping("/getCode")
    public ResponseResult getCode(String codeId) {
        Map<String, Object> map = new HashMap<>();
        //判断是否需要重新随机生成一个id
        if (codeId == null || codeId.trim().isEmpty()) {
            //获取codeid
            String id = IdUtil.getSnowflakeNextIdStr();//随机生成一个id，
            codeId = REDIS_REFIX + id;
            System.out.println(codeId);
        }
        //设置验证码图片长、宽、验证码字符数、干扰线宽度
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(120, 30, 1, 10);
        //设置字体样式和大小
        lineCaptcha.setFont(new Font("仿宋", Font.BOLD, 20));
        //获取验证码
        String code = lineCaptcha.getCode();
//        System.out.println(codeId + "=" + code);
        //把验证码 保存到 session （实际开发过程中保存到redis中）
//        session.setAttribute("verfityCode", code);
        redis.set(codeId, code, 120);
        //转为Base64字符串
        String imageBase64 = lineCaptcha.getImageBase64Data();
        map.put("base64Code", imageBase64);
        map.put("codeId", codeId);
        return ResponseResult.okResult(map);
    }

    //验证Token有效性
    @GetMapping("verifyToken")
    public ResponseResult verifyToken(HttpServletRequest request) {
        // 1. 从请求头获取Token
        String token = request.getHeader("Authorization");
        if (token == null || token.trim().isEmpty()) {
            throw new BusinessException(ResultStatusEnum.LOGIN_ERROR);
        }
        // 2. 处理Token前缀（如"Bearer "）
        token = JwtUtil.handlePrefix(token);
        // 解析用户ID
        Integer userId = JwtUtil.getUserId(token);
        // 3. 对比Redis中的Token
        if (token.equals(redis.get(RedisConstant.USER_LOGIN_KEY + userId))) {
            return ResponseResult.okResult();
        }
        throw new BusinessException(ResultStatusEnum.LOGIN_ERROR);
    }

}
